package com.yet.source;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.PropertySource;
import org.springframework.util.ReflectionUtils;

public class CenterPropertyValues<T> implements PropertyValues {

	private final Class<?> clz;
	private final List<KeyPropertyValue> propertyValues = new ArrayList<>();

	public CenterPropertyValues(PropertySource<T> propertySource, Class<?> clz) {
		super();
		this.clz = clz;
		parse();
	}

	private void parse() {
		ReflectionUtils.doWithFields(clz, f -> {
			if (f.isAnnotationPresent(Value.class)) {
				Value[] value = f.getAnnotationsByType(Value.class);
				if (value.length != 0) {
					Value val = value[0];
					String config = null;
					if ((config = PropertySourcesPropertyResolverHolder.resolver
							.resolvePlaceholders(val.value())) != null && !config.equals(val.value())) {
						final String fConfig = config;
						PropertySourcesPropertyResolverHolder.strictHelper.replacePlaceholders(val.value(), k -> {
							propertyValues.add(new KeyPropertyValue(k, f.getName(), fConfig));
							return k;
						});
						return;
					}
				}
			}
		});
	}

	@Override
	public PropertyValue[] getPropertyValues() {
		return propertyValues.toArray(new PropertyValue[propertyValues.size()]);
	}

	@Override
	public PropertyValue getPropertyValue(String propertyName) {
		return null;
	}

	@Override
	public PropertyValues changesSince(PropertyValues old) {
		return null;
	}

	@Override
	public boolean contains(String propertyName) {
		return propertyValues.stream().filter(p -> p.getName().equals(propertyName)).count() == 1;
	}

	@Override
	public boolean isEmpty() {
		return false;
	}

	public List<KeyPropertyValue> getKeyPropertyValue() {
		return propertyValues;
	}

}
